from __future__ import annotations

import re
from pathlib import Path
from typing import Dict, Any, List


class TemplateRenderer:
    """简单的HTML模板渲染器,支持变量替换和循环"""

    def __init__(self, template_dir: str = "templates"):
        self.template_dir = Path(template_dir)

    def render(self, template_name: str, context: Dict[str, Any]) -> str:
        """
        渲染模板

        Args:
            template_name: 模板文件名 (如 "welcome.html")
            context: 模板变量字典

        Returns:
            渲染后的HTML字符串

        Example:
            renderer = TemplateRenderer()
            html = renderer.render("welcome.html", {
                "username": "张三",
                "register_time": "2025-10-21",
                "activation_link": "https://example.com/activate"
            })
        """
        template_path = self.template_dir / template_name

        if not template_path.exists():
            raise FileNotFoundError(f"Template not found: {template_path}")

        template_content = template_path.read_text(encoding="utf-8")

        # 渲染模板
        return self._render_template(template_content, context)

    def _render_template(self, template: str, context: Dict[str, Any]) -> str:
        """内部渲染函数"""

        # 1. 处理简单变量 {{variable}}
        def replace_var(match):
            var_name = match.group(1).strip()
            value = context.get(var_name, "")
            return str(value) if value is not None else ""

        rendered = re.sub(r'\{\{([^}]+)\}\}', replace_var, template)

        return rendered

    def render_from_string(self, template_string: str, context: Dict[str, Any]) -> str:
        """
        从字符串渲染模板(不读取文件)

        Args:
            template_string: 模板字符串
            context: 模板变量字典

        Returns:
            渲染后的HTML字符串
        """
        return self._render_template(template_string, context)


def render_table_rows(rows: List[Dict[str, Any]], columns: List[str]) -> str:
    """
    辅助函数: 渲染表格行

    Args:
        rows: 行数据列表,每行是一个字典
        columns: 列名列表

    Returns:
        HTML表格行字符串

    Example:
        rows = [
            {"date": "2025-10-20", "visits": 1000, "rate": "5.2%", "revenue": "¥2000"},
            {"date": "2025-10-21", "visits": 1200, "rate": "6.1%", "revenue": "¥2500"},
        ]
        html = render_table_rows(rows, ["date", "visits", "rate", "revenue"])
    """
    html_rows = []
    for row in rows:
        cells = [f"<td>{row.get(col, '')}</td>" for col in columns]
        html_rows.append(f"<tr>{''.join(cells)}</tr>")

    return "\n".join(html_rows)


def render_list_items(items: List[str], item_class: str = "") -> str:
    """
    辅助函数: 渲染列表项

    Args:
        items: 列表项内容
        item_class: li标签的CSS类名(可选)

    Returns:
        HTML列表项字符串

    Example:
        items = ["完成用户注册功能", "修复登录bug", "优化性能"]
        html = render_list_items(items)
    """
    class_attr = f' class="{item_class}"' if item_class else ""
    li_items = [f"<li{class_attr}>{item}</li>" for item in items]
    return "\n".join(li_items)


# 便捷函数
def quick_render(template_name: str, context: Dict[str, Any], template_dir: str = "templates") -> str:
    """
    快速渲染函数

    Args:
        template_name: 模板文件名
        context: 模板变量
        template_dir: 模板目录(默认 "templates")

    Returns:
        渲染后的HTML
    """
    renderer = TemplateRenderer(template_dir)
    return renderer.render(template_name, context)
